package com.dameng.system.controller;

import com.dameng.system.entity.SystemUser;
import com.dameng.system.service.SystemMenuService;
import com.dameng.system.service.SystemUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class IndexController {
    @Resource
    SystemMenuService systemMenuService;

    @Resource
    SystemUserService systemUserService;

    @GetMapping({"/","/index"})
    public String index(ModelMap model) {
        return "index";
    }

    @PostMapping("/getMenu")
    @ResponseBody
    public Object getMenu(Authentication auth) {
        SystemUser user = (SystemUser) auth.getPrincipal();
        // 登录账号：auth.getName() 或 user.getName()
        return systemMenuService.getMenuByUserId(user.getUserId());
    }

    @PostMapping("/getMenuDetail")
    @ResponseBody
    public Object getMenuDetail(Authentication auth, String menuId) {
        SystemUser user = (SystemUser) auth.getPrincipal();
        return systemMenuService.childMenuByUserId(user.getUserId(), menuId);
    }

    @PostMapping("/savePwd")
    @ResponseBody
    public boolean savePwd(String pwd, Authentication auth) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(pwd);
        SystemUser user = (SystemUser) auth.getPrincipal();
        SystemUser sysUser = new SystemUser().setUserId(user.getUserId()).setPassword(encodedPassword);
        return systemUserService.updateById(sysUser);
    }

}
